<?php
/**
 * Created by PhpStorm
 * User: shen.zk
 * Date: 2023/8/26
 * Time: 18:25
 * Comment: ''
 */

namespace App\Service\Common;

use App\Common\ResponseCode;
use App\Common\Tools;
use App\Exceptions\BusinessException;
use App\Extensions\bservice\Bservice;
use App\Params\Common\LoginParams;
use App\Repository\MemberRepo;
use App\Repository\MerchantsInfoRepo;
use App\Service\BaseService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Params\Common\AuthenticationMemberParams;
use App\Extensions\stepbystepchain\StepByStepChainService;
use App\Params\Common\MemberParams;
use App\Service\Common\MerchantsService;
use App\Repository\GoodsRepo;
use App\Repository\StatisticsRepo;
use App\Repository\SpecialRepo;
use App\Params\Common\GoodsUgcBindParams;
use App\Repository\SpecialPrivilegeUgcOrderRepo;
use App\Params\Common\MemberEarliestOrderTimeParams;
use App\Repository\SpecialOrderRepo;

class MemberService extends BaseService
{
    /**
     * 用户登入
     * @param LoginParams $params
     * @return array
     * @author shen.zk
     * @date 2023-08-27 11:42
     */
    public function LoginService(LoginParams $params)
    {
        $phone = $params->getPhone();
        // 手机号校验
        $checkPhone = Tools::verifyMobileFormat($phone);
        if (!$checkPhone)
            throw new BusinessException(ResponseCode::PHONE_ERR);
        $merchant_id = $params->getMid();

        // 用户登入
        $memberInfo = MemberRepo::getInstance()->getByPhoneRepo($phone);
        if (empty($memberInfo))
            throw new BusinessException(ResponseCode::USERNOTFUND);

        // 获取创作者是否存在
        $merchantsInfo = MerchantsInfoRepo::getInstance()->getByMerchantIdRepo($merchant_id);
        if (empty($merchantsInfo))
            throw new BusinessException(ResponseCode::MERCHANTSNOTFUND);

        // 生成token
        $userData['access_token'] = auth('api')->fromUser($memberInfo);

        return $userData;
    }

    /**
     * 用户注册+认证
     * @return bool
     * @throws BusinessException
     * @author shen.zk
     * @date 2023-09-04 16:38
     */
    public function registerAuthMemberService()
    {
        $phone = request('phone');
        if (empty($phone))
            throw new BusinessException(ResponseCode::PARAM_ILLEGAL, ['error' => '手机号不能为空']);

        // 手机号校验
        $checkPhone = Tools::verifyMobileFormat($phone);
        if (!$checkPhone)
            throw new BusinessException(ResponseCode::PHONE_ERR);

        $id_card = request('id_card');
        if (empty($id_card))
            throw new BusinessException(ResponseCode::PARAM_ILLEGAL, ['error' => '身份证号码不能为空']);

        $name = request('name');
        if (empty($name))
            throw new BusinessException(ResponseCode::PARAM_ILLEGAL, ['error' => '姓名不能为空']);

        // 根据手机号校验是否存在
        $memberInfo = MemberRepo::getInstance()->getByPhoneRepo($phone);
        Log::info("获取用户信息" . json_encode($memberInfo, JSON_UNESCAPED_UNICODE));
        if (!empty($memberInfo)){
            //查询用户扩展信息
            $extendInfo = MemberRepo::getInstance()->getByMemrberId($memberInfo->id);
            if ( !empty($extendInfo) && $extendInfo->real_name_status == 2){
                throw new BusinessException(ResponseCode::USEREXIST);
            }else{
                throw new BusinessException(ResponseCode::USER_REAL_NAME_NOT_FINISHED);
            }
        }
        // 组装会员注册请求参数
        $member_option = [
            "appinit_type"    => 1,
            'member_group_id' => 1,
            'login_num'       => 1,
            'login_name'      => $phone,
            'mobile'          => $phone,
            'password'        => sha1($phone),
            'create_time'     => date('Y-m-d H:i:s'),
            'update_time'     => date('Y-m-d H:i:s'),
            'money'           => 0,
            'integral'        => 0,
            'virtual_money'   => 0,
            'freeze_money'    => 0,
        ];

        // 创建钱包地址
        $address = StepByStepChainService::getInstance()->createWalletAddress();
        //$member_option['account_address'] = $address['data'];
        $member_option['ca_account_address'] = $address['data'];

        // 写入用户数据
        DB::beginTransaction();
        try {
            $memberId = MemberRepo::getInstance()->addMemberInfoRepo($member_option);
            if (empty($memberId)) {
                DB::rollBack();
                throw new BusinessException(ResponseCode::REGISTERERR);
            }

            // 调用第三方服务获取身份证号码与真实姓名是否一致
            $save_data = [
                "id_card"     => $id_card,
                "nickname"    => $name,
                "real_time"   => date('Y-m-d H:i:s'),
                "order_total" => 0,
                'member_id'   => $memberId
            ];

            // 测试环境
            if (env('APP_ENV') == 'test') {
                $result['head']['responseStatus'] = '00';
                $result['body']['platformCode'] = '00000';
            }

            // 生产环境
            if (env('APP_ENV') == 'pro') {
                $result = Bservice::getInstance()->authenticationInfo($id_card, $name);
            }


            if ($result['head']['responseStatus'] != '00' && $result['body']['platformCode'] != '00000') {
                $save_data['real_name_status'] = 3;
            } else {
                $save_data['real_name_status'] = 2;
            }
            $save_data['real_time'] = date('Y-m-d H:i:s');
            $extendId = MemberRepo::getInstance()->memberExtendInfoRepo($save_data);
            if (empty($extendId)) {
                DB::rollBack();
                throw new BusinessException(ResponseCode::REGISTERERR);
            }
            DB::commit();
            return true;
        } catch (\Exception $e) {
            Log::error('[用户注册异常]' . $e->getMessage());
            DB::rollBack();
            throw new BusinessException(ResponseCode::REGISTERERR);
        }
    }

    /**
     * 用户注册
     * @return bool
     * @throws BusinessException
     * @author shen.zk
     * @date 2023-08-27 12:16
     */
    public function registerMemberService()
    {
        $phone = request('phone');
        if (empty($phone))
            throw new BusinessException(ResponseCode::PARAM_ILLEGAL, ['error' => '归属创作者不能为空']);

        $merchant_id = request('mid');
        if (empty($merchant_id))
            throw new BusinessException(ResponseCode::PARAM_ILLEGAL, ['error' => '商户号不能为空']);

        // 根据手机号校验是否存在
        $memberInfo = MemberRepo::getInstance()->getByPhoneRepo($phone);
        if (!empty($memberInfo))
            throw new BusinessException(ResponseCode::USEREXIST);


        // 组装会员注册请求参数
        $member_option = [
            "appinit_type"    => 1,
            'member_group_id' => 1,
            'login_num'       => 1,
            'login_name'      => $phone,
            'mobile'          => $phone,
            'password'        => sha1($phone),
            'create_time'     => date('Y-m-d H:i:s'),
            'update_time'     => date('Y-m-d H:i:s'),
            'money'           => 0,
            'integral'        => 0,
            'virtual_money'   => 0,
            'freeze_money'    => 0,
        ];

        // 创建钱包地址
        $address = StepByStepChainService::getInstance()->createWalletAddress();
        //$member_option['account_address'] = $address['data'];
        $member_option['ca_account_address'] = $address['data'];

        // 写入用户数据
        DB::beginTransaction();
        try {
            $memberId = MemberRepo::getInstance()->addMemberInfoRepo($member_option);
            if (empty($memberId)) {
                DB::rollBack();
                throw new BusinessException(ResponseCode::REGISTERERR);
            }

            $memberExtend = [
                'real_name_status' => 0,
                'member_id'        => $memberId,
                'create_time'      => date("Y-m-d H:i:s"),
                'order_total'      => 0,
            ];
            $extendId = MemberRepo::getInstance()->memberExtendInfoRepo($memberExtend);
            if (empty($extendId)) {
                DB::rollBack();
                throw new BusinessException(ResponseCode::REGISTERERR);
            }

            DB::commit();
        } catch (\Exception $e) {
            Log::error('[用户注册异常]' . $e->getMessage());
            DB::rollBack();
            throw new BusinessException(ResponseCode::REGISTERERR);
        }

        return true;
    }

    /**
     * 实名认证
     * @param AuthenticationMemberParams $params
     * @return bool
     * @throws BusinessException
     * @author shen.zk
     * @date 2023-09-04 15:26
     */
    public function authenticationMemberService(AuthenticationMemberParams $params)
    {
        // 获取重复认证
        DB::beginTransaction();
        $extendInfo = MemberRepo::getInstance()->getByMemrberId($params->getMemberId());
        if (empty($extendInfo)) {
            DB::rollBack();
            throw new BusinessException(ResponseCode::USERNOTFUND);
        }

        // 待审核
        if ($extendInfo->real_name_status == 1) {
            DB::rollBack();
            throw new BusinessException(ResponseCode::REALNAMESTATUSCHECK);
        }


        // 审核通过
        if ($extendInfo->real_name_status == 2) {
            DB::rollBack();
            throw new BusinessException(ResponseCode::REALNAMESTATUSPASSED);
        }


        // 实名驳回
        if ($extendInfo->real_name_status == 3) {
            DB::rollBack();
            throw new BusinessException(ResponseCode::REALNAMESTATUSREJECT);
        }

        // 调用第三方服务获取身份证号码与真实姓名是否一致
        $save_data = [
            "id_card"   => $params->getIdCard(),
            "nickname"  => $params->getName(),
            "real_time" => date('Y-m-d H:i:s'),
        ];
        // 测试环境
        if (env('APP_ENV') == 'test') {
            $result['head']['responseStatus'] = '00';
            $result['body']['platformCode'] = '00000';
        }

        // 生产环境
        if (env('APP_ENV') == 'pro') {
            $result = Bservice::getInstance()->authenticationInfo($params->getIdCard(), $params->getName());
        }

        if ($result['head']['responseStatus'] != '00' && $result['body']['platformCode'] != '00000') {
            $save_data['real_name_status'] = 3;
        } else {
            $save_data['real_name_status'] = 2;
        }

        $extendId = MemberRepo::getInstance()->memberExtendInfoRepo($save_data);
        if (empty($extendId)) {
            DB::rollBack();
            throw new BusinessException(ResponseCode::REGISTERERR);
        }
        return true;
    }

    /**
     * 获取用户信息
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     * @throws BusinessException
     * @author shen.zk
     * @date 2023-09-07 10:21
     */
    public function getUserInfoService()
    {
        $member_id = request('member_id');
        if (empty($member_id))
            throw new BusinessException(ResponseCode::USERNOTFUND);
        return MemberRepo::getInstance()->getByMemrberId($member_id);
    }

    /**
     * 用户的藏品列表
     * @param MemberParams $params
     * @return array
     * @throws BusinessException
     * @throws \RedisException
     * Author:xsc
     * Time:2023/10/8 16:32
     */
    public function specialList(MemberParams $params)
    {
        $access_mid = $params->getMid();
        $mobile = $params->getMobile();
        $page = $params->getPage() ?: 1;
        $page_size = $params->getPageSize() ?: 20;
        $title = $params->getTitle() ?: '';//藏品名称,可选

        $page_size = $page_size > 100 ? 100 : $page_size;

        $merchants_id = 0;
        if ($access_mid) {
            // 接入商户信息
            $merchants_info = MerchantsService::getInstance()->getInfoWithCache($access_mid);
            if (!$merchants_info) {
                throw new BusinessException(ResponseCode::MERCHANTS_NOT_FUND);
            }

            // 商户id
            $merchants_id = $merchants_info['merchants_id'];
        }

        // 用户信息
        $member = MemberRepo::getInstance()->getInfoByMobile($mobile);
        if (!$member) {
            throw new BusinessException(ResponseCode::USERNOTFUND);
        }

        // 用户id
        $member_id = $member['member_id'];

        $where = ['member_id' => $member_id, 'page' => $page, 'page_size' => $page_size,];
        if ($merchants_id) {
            $where['merchants_id'] = $merchants_id;
        }
        if ($title) {
            $where['title'] = $title;
        }

        $total = GoodsRepo::getInstance()->getUsableGoodsList($where, 2, 1);

        $special_list = GoodsRepo::getInstance()->getUsableGoodsList($where, 2);

        $list = [];
        foreach ($special_list as $value) {
            $list[] = [
                'special_id'   => $value->special_id,
                'special_type' => $value->special_type,
                'title'        => $value->title,
                'thumb'        => $value->thumb,
                'base_price'   => $value->base_price,
                'cast_count'   => $value->ca_cast_count,
                'album_name'   => $value->album_name,
                'create_time'  => $value->special_create_time,
                'user_name'    => $value->user_name,
                'portrait'     => $value->portrait,
                'count'        => $value->cnt,
            ];
        }
        $data = [
            'total' => $total,
            'list'  => $list,
        ];

        return $data;
    }

    /**
     * 用户的商品列表
     * @param MemberParams $params
     * @return array
     * @throws BusinessException
     * @throws \RedisException
     * Author:xsc
     * Time:2023/9/19 18:17
     */
    public function goodsList(MemberParams $params)
    {
        $access_mid = $params->getMid();
        $mobile = $params->getMobile();
        $page = $params->getPage() ?: 1;
        $page_size = $params->getPageSize() ?: 20;

        $special_id = $params->getSpecialId() ?: 0;//藏品id,可选

        $page_size = $page_size > 100 ? 100 : $page_size;

        $merchants_id = 0;
        if ($access_mid) {
            // 接入商户信息
            $merchants_info = MerchantsService::getInstance()->getInfoWithCache($access_mid);
            if (!$merchants_info) {
                throw new BusinessException(ResponseCode::MERCHANTS_NOT_FUND);
            }

            // 商户id
            $merchants_id = $merchants_info['merchants_id'];
        }

        // 用户信息
        $member = MemberRepo::getInstance()->getInfoByMobile($mobile);
        if (!$member) {
            throw new BusinessException(ResponseCode::USERNOTFUND);
        }

        // 用户id
        $member_id = $member['member_id'];

        $where = ['member_id' => $member_id, 'page' => $page, 'page_size' => $page_size,];
        if ($merchants_id) {
            $where['merchants_id'] = $merchants_id;
        }
        if ($special_id) {
            $where['special_id'] = $special_id;
        }

        $total = GoodsRepo::getInstance()->getUsableGoodsList($where, 1, 1);

        $goods_list = GoodsRepo::getInstance()->getUsableGoodsList($where, 1);

        $list = [];
        foreach ($goods_list as $value) {
            $list[] = [
                'goods_id'     => $value->goods_id,
                'type'         => $value->type,
                'code'         => $value->code,
                'price'        => $value->price,
                'status'       => $value->status,
                'sell_status'  => $value->sell_status,
                'chain_mark'   => $value->chain_mark,
                'create_time'  => $value->create_time,
                'special_id'   => $value->special_id,
                'special_type' => $value->special_type,
                'title'        => $value->title,
                'thumb'        => $value->thumb,
                'cast_count'   => $value->ca_cast_count,
                'album_name'   => $value->album_name,
            ];
        }

        $data = [
            'total' => $total,
            'list'  => $list,
        ];

        return $data;
    }

    /**
     * 用户ugc赋能订单
     * @param GoodsUgcBindParams $params
     * @return array[]
     * @throws BusinessException
     * Author:xsc
     * Time:2023/10/10 17:47
     */
    public function ugcOrderList(GoodsUgcBindParams $params)
    {
        $mobile = $params->getMobile();
        $goods_id = $params->getGoodsId();
        $third_no = $params->getThirdNo();

        // 用户信息
        $member = MemberRepo::getInstance()->getInfoByMobile($mobile);
        if (!$member) {
            throw new BusinessException(ResponseCode::USERNOTFUND);
        }

        // 用户id
        $member_id = $member['member_id'];

        // 商品详情
        $goods_info = GoodsRepo::getInstance()->getInfo($goods_id, $member_id);
        if (!$goods_info) {
            throw new BusinessException(ResponseCode::GOODS_NOT_FUND);
        }

        $where = [
            'goods_id'       => $goods_id,
            'from_member_id' => $member_id,
            'thirdNo'        => $third_no,
        ];
        $order_list = SpecialPrivilegeUgcOrderRepo::getInstance()->list($where);
        if (!$order_list) {
            throw new BusinessException(ResponseCode::GOODS_UGC_ORDER_NOT_EXISTS);
        }

        $list = [];
        foreach ($order_list as $value) {
            $list[] = [
                'ordersn'        => $value['ordersn'],
                'status'         => $value['status'],
                'special_id'     => $value['special_id'],
                'goods_id'       => $value['goods_id'],
                'type'           => $value['type'],
                'rp_type'        => $value['rp_type'],
                'rp_amount'      => $value['rp_amount'],
                //'mer_id'         => $value['mer_id'],
                'from_member_id' => $value['from_member_id'],
                'coupon_code'    => $value['coupon_code'],
                'thirdNo'        => $value['thirdNo'],
                'end_time'       => $value['end_time'],
                'create_time'    => $value['create_time'],
            ];
        }

        $data = [
            'list' => $list,
        ];

        return $data;
    }

    /**
     * 查询用户最早下单时间(批量)
     * @param MemberEarliestOrderTimeParams $params
     * @return array[]
     * @throws BusinessException
     * Author:xsc
     * Time:2023/11/10 15:06
     */
    public function earliestOrderTime(MemberEarliestOrderTimeParams $params)
    {
        $mobiles = $params->getMobiles();

        $mobile_arr = json_decode($mobiles, true);
        if (!$mobile_arr || !is_array($mobile_arr)) {
            throw new BusinessException(ResponseCode::PHONE_ERR, ['error' => '手机号格式错误']);
        }

        $mobile_arr = array_unique($mobile_arr);
        if (count($mobile_arr) > 100) {
            throw new BusinessException(ResponseCode::PHONE_ERR, ['error' => '请输入少于100个手机号']);
        }

        $data = SpecialOrderRepo::getInstance()->getEarliestOrderTime($mobile_arr);

        $list = [];
        foreach ($data as $value) {
            $list[] = [
                'mobile'      => $value['mobile'],
                'create_time' => $value['create_time'],
            ];
        }

        $data = [
            'list' => $list,
        ];

        return $data;
    }



}
